package thread.threaddemo;

/**
 * @Author: wenjingyuan
 * @Date: 2022/11/18/18:01
 * @Description:Synchronized修饰代码块
 */
public class ThreadSynchronized3 {
    private  static int number=0;
    //定义一个内部类
    static class Counter{
        private static int MAX_Counter=100000;
        //我们还可以自定义锁对象
        private Object myLock=new Object();
        public  void incr(){
            for (int i = 0; i < MAX_Counter; i++) {
                synchronized (myLock){
                    number++;
                }

            }
        }
        public  void decr(){
            for (int i = 0; i < MAX_Counter; i++) {
                synchronized (myLock){
                    number--;
                }
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadSynchronized2.Counter counter=new ThreadSynchronized2.Counter();
        Thread t1=new Thread(()->{
            counter.incr();
        });
        t1.start();
        Thread t2=new Thread(()->{
            counter.decr();
        });
        t2.start();

        t1.join();
        t2.join();

        System.out.println("最终的结果"+ number);
    }
}
